package cn.antcore.common.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.UUID;

/**
 * 请求拦截器
 * <br>
 * Created by Hong 2024/5/28
**/
@Component
public class AccessInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AccessInterceptor.class);

    @Resource
    private ObjectMapper mapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String origin = request.getHeader("Origin");
        if (!StringUtils.hasText(origin)) {
            origin = "*";
        }
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cookie, Access-Request-Id, Access-AppId, Access-Timestamp, Access-Nonce, Access-Sign, X-Auth-Token, Access-Sign-Type");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String requestId = UUID.randomUUID().toString().replaceAll("-", "");
        MDC.put("requestId", requestId);

        //禁止预检
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return false;
        }

        String path = request.getRequestURI();
        //记录请求路径和该请求的起始时间
        request.setAttribute("path", path);
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //SKIP
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws JsonProcessingException {
        String path = (String) request.getAttribute("path");
        long startTime = (long) request.getAttribute("startTime");

        long endTime = System.currentTimeMillis();
        //计算时间差
        long costTime = endTime - startTime;

        String builder = "[" + request.getMethod().toUpperCase() + "]" + " " +
                path + " " +
                costTime + " " +
                mapper.writeValueAsString(request.getParameterMap());

        log.info(builder);
    }
}
